package com.mes.web.controller.llm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mes.entity.check.PatrolCheck;
import com.mes.entity.check.ReportCheck;
import com.mes.entity.check.TreeCheck;
import com.mes.entity.llm.Clazz;
import com.mes.entity.llm.FillRecord;
import com.mes.entity.llm.Node;
import com.mes.entity.llm.SaleDeliveryReport;
import com.mes.entity.tdd.Staff;
import com.mes.entity.warning.Warning;
import com.mes.service.jyy.ReportService;
import com.mes.service.llm.ChartLlmService;
import com.mes.service.llm.ClazzService;
import com.mes.service.warning.WarningService;
import com.mes.utils.ResponseUtil;
import com.mes.utils.PushExample;

import net.sf.json.JSONObject;

/**
 * 报表
 * @Title:LlmReportController
 * @Package com.mes.web.controller.llm
 * @author llm
 * @date 2019年5月31日
 * @version 1.0
 */
@Controller
@RequestMapping("/llmReport")
public class LlmReportController {

	@Resource ClazzService ClazzService;
	@Resource ChartLlmService ChartLlmService;
	@Resource WarningService warningService;
	@Resource ReportService reportService;
	/**
	 * 财务报表
	 */
	@RequestMapping("reslist")
    public void getReslist(HttpServletRequest request, HttpServletResponse response, HttpSession session){

		String ename = "";
		String tablename = "";
		String tablename2 = "";
		Staff staff = (Staff) session.getAttribute("staff");
		if(staff != null) {
			Long staffid = staff.getStaffid();
			
			//根据员工id查询，该员工账套的英文名称
			ename = reportService.selectBooksEnameBysid(staffid);
			
			tablename = "jyy_books_chart_"+ename;
			tablename2 = "jyy_books_clazz_"+ename;
		}
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "no");
		
		//获得树形结构的json数据(方法)
        Node tree = getTreeJson(tablename, tablename2);
        
        Node n = tree.zxPraseTree(tree);//把树形结构数据按中序遍历顺序，加入list
        List<Node> reslist = n.getNodes();//获得上面的list
        List<Node> list = new ArrayList<Node>();
        for(Node node : reslist) {//去掉null节点
            if(null != node) {
                if(node.getId() != null) {
                    list.add(node);
                }
            }
        }
        jsonObject.put("result", "ok");
	    jsonObject.put("data", list);
        try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

     public Node getTreeJson(String tablename, String tablename2) {
    	 Map<String, Object> map = getTimeMap();
    	 map.put("tablename", tablename);
    	 map.put("tablename2", tablename2);
         List<Clazz> reslist = ClazzService.queryAllByTime(map); //从数据库加载所有数据，得到list
         List<Node> nodes = new ArrayList<Node>();
         for(Clazz res : reslist){
             Node node = new Node();
             node.setMonthMoney(res.getMonthMoney());
             node.setYearMoney(res.getYearMoney());
             node.setId(res.getId());
             node.setFid(res.getFid());
             node.setCname(res.getCname());
             nodes.add(node);
             node = null;
         }
         Node tree = new Node();
         Node mt = tree.createTree(nodes);//把list转化成tree
         //System.out.println(tree.iteratorTree(mt));//遍历打印
         return mt;
     }
     
     public Map<String, Object> getTimeMap(){
    	 Map<String, Object> map = new HashMap<>();
    	 Calendar cale = null;  
         cale = Calendar.getInstance();  
         int year = cale.get(Calendar.YEAR);  
         int month = cale.get(Calendar.MONTH) + 1; 
    	 switch(month){
	    	 case 1:
		    	 map.put("monthName", "jan");
		    	 break;
	    	 case 2:
		    	 map.put("monthName", "feb");
		    	 break;
	    	 case 3:
		    	 map.put("monthName", "mar");
		    	 break;
	    	 case 4:
		    	 map.put("monthName", "apr");
		    	 break;
	    	 case 5:
		    	 map.put("monthName", "may");
		    	 break;
	    	 case 6:
		    	 map.put("monthName", "june");
		    	 break;
	    	 case 7:
		    	 map.put("monthName", "july");
		    	 break;
	    	 case 8:
		    	 map.put("monthName", "aug");
		    	 break;
	    	 case 9:
		    	 map.put("monthName", "sept");
		    	 break;
	    	 case 10:
		    	 map.put("monthName", "oct");
		    	 break;
	    	 case 11:
		    	 map.put("monthName", "nov");
		    	 break;
	    	 case 12:
		    	 map.put("monthName", "dec");
		    	 break;
	    	 default:
		    	 break;	 
    	 }
    	 map.put("year", year+"");
    	 return map;
     }
     
     /**
      * 销售订单发货统计表
      * @param dateTime
      * @param customerId
      * @param response
      */
     @RequestMapping("/selectSaleDelivery")
     public void selectSaleDelivery(String dateTime, String customerId, HttpServletResponse response){
    	 Map<String, Object> map = new HashMap<>();
    	 List<SaleDeliveryReport> list = new ArrayList<>();
    	 if(customerId != null && !"".equals(customerId)){
    		 if(dateTime != null && !"".equals(dateTime)){
    			 map.put("dateTime", dateTime);
    		 }else{
    			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    			 map.put("dateTime", sdf.format(new Date()));
    		 }
    		 map.put("customerId", Long.parseLong(customerId));
    		 list = ChartLlmService.selectSaleDelivery(map);
    	 }
    	 JSONObject jsonObject=new JSONObject();
 		jsonObject.put("total", list.size());
 		jsonObject.put("rows", list);
 		try {
 			ResponseUtil.write(response, jsonObject);
 		} catch (Exception e) {
 			e.printStackTrace();
 		}
     }
     
     /**
      * 订单准时发货率统计表
      * @param dateTime
      * @param customerId
      * @param response
      */
     @RequestMapping("/selectPunctualitySale")
     public void selectPunctualitySale(String dateTime, String customerId, HttpServletResponse response){
    	 Map<String, Object> map = new HashMap<>();
    	 List<SaleDeliveryReport> list = new ArrayList<>();
    	 if(customerId != null && !"".equals(customerId)){
    		 if(dateTime != null && !"".equals(dateTime)){
    			 map.put("dateTime", dateTime);
    		 }else{
    			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    			 map.put("dateTime", sdf.format(new Date()));
    		 }
    		 map.put("customerId", Long.parseLong(customerId));
    		 list = ChartLlmService.selectPunctualitySale(map);
    	 }
    	 JSONObject jsonObject=new JSONObject();
    	 jsonObject.put("total", list.size());
 		 jsonObject.put("rows", list);
 		 try {
 			ResponseUtil.write(response, jsonObject);
 		 } catch (Exception e) {
 			e.printStackTrace();
 		 }
     }
     
     /**
      * 客户返品比率统计表 
      * @param dateTime
      * @param customerId
      * @param response
      */
     @RequestMapping("/selectReturnRatil")
     public void selectReturnRatil(String dateTime, String customerId, HttpServletResponse response){
    	 Map<String, Object> map = new HashMap<>();
    	 List<SaleDeliveryReport> list = new ArrayList<>();
    	 if(customerId != null && !"".equals(customerId)){
    		 if(dateTime != null && !"".equals(dateTime)){
    			 map.put("dateTime", dateTime);
    		 }else{
    			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    			 map.put("dateTime", sdf.format(new Date()));
    		 }
    		 map.put("customerId", Long.parseLong(customerId));
    		 list = ChartLlmService.selectReturnRatil(map);
    	 }
    	 JSONObject jsonObject=new JSONObject();
    	 jsonObject.put("total", list.size());
 		 jsonObject.put("rows", list);
 		 try {
 			ResponseUtil.write(response, jsonObject);
 		 } catch (Exception e) {
 			e.printStackTrace();
 		 }
     }
     
     /**
      * 完成品库存日报表
      * @param dateTime
      * @param customerId
      * @param response
      */
     @RequestMapping("/selectProductStockByDay")
     public void selectProductStockByDay(String dateTime, HttpServletResponse response){
    	 Map<String, Object> map = new HashMap<>();
    	 List<SaleDeliveryReport> list = new ArrayList<>();
		 if(dateTime != null && !"".equals(dateTime)){
			 map.put("dateTime", dateTime);
		 }else{
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			 map.put("dateTime", sdf.format(new Date()));
		 }
		 list = ChartLlmService.selectProductStockByDay(map);
    	 JSONObject jsonObject=new JSONObject();
    	 jsonObject.put("total", list.size());
 		 jsonObject.put("rows", list);
 		 try {
 			ResponseUtil.write(response, jsonObject);
 			map = null;
 			list = null;
 			jsonObject = null;
 		 } catch (Exception e) {
 			e.printStackTrace();
 		 }
     }
     
     /**
      * 资材库存日报表
      * @param dateTime
      * @param customerId
      * @param response
      */
     @RequestMapping("/selectMaterielStockByDay")
     public void selectMaterielStockByDay(String dateTime, HttpServletResponse response){
    	 Map<String, Object> map = new HashMap<>();
    	 List<SaleDeliveryReport> list = new ArrayList<>();
		 if(dateTime != null && !"".equals(dateTime)){
			 map.put("dateTime", dateTime);
		 }else{
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			 map.put("dateTime", sdf.format(new Date()));
		 }
		 list = ChartLlmService.selectMaterielStockByDay(map);
    	 JSONObject jsonObject=new JSONObject();
    	 jsonObject.put("total", list.size());
 		 jsonObject.put("rows", list);
 		 try {
 			ResponseUtil.write(response, jsonObject);
 			map = null;
 			list = null;
 			jsonObject = null;
 		 } catch (Exception e) {
 			e.printStackTrace();
 		 }
     }
     
     /**
      * 查询质检填报记录并推送通知
      */
     @RequestMapping("/selectFillRecordByDay")
     public void selectFillRecordByDay(){
    	 Date date = new Date();
    	 Map<String, Object> map = new HashMap<>();
    	 Warning w = new Warning();
    	 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	 String today = sdf.format(date);
    	 map.put("today", today);
    	 //查询质检部门员工的权限
    	 List<FillRecord> list = ChartLlmService.selectMenuByDepartment();
    	 int i;
    	 //根据权限查当天的填报记录
    	 for(FillRecord fr : list){
    		 if(fr != null){
    			 i = 0;
    			 if(fr.getMenuId() == 77 ){
    				 map.put("userId", fr.getUserId());
    				 List<TreeCheck> tclist =  ChartLlmService.selectTreeCheckFillRecord(map);
    				 if(tclist.size() == 0){
    					 i = 1;
    				 }
    			 }else if(fr.getMenuId() == 78 ){
    				 map.put("userId", fr.getUserId());
    				 List<PatrolCheck> tclist =  ChartLlmService.selectPatrolCheckFillRecord(map);
    				 if(tclist.size() == 0){
    					 i = 1;
    				 }
    			 }else if(fr.getMenuId() == 79 ){
    				 map.put("userId", fr.getUserId());
    				 List<ReportCheck> tclist =  ChartLlmService.selectReportCheckFillRecord(map);
    				 if(tclist.size() == 0){
    					 i = 1;
    				 }
    			 }
    			 if(i == 1){
    				 w.setWsid(fr.getUserId());
        			 w.setWtype(fr.getMenuName());
        			 w.setWdate(today);
        			 w.setWstare("0");
        			 PushExample.testSendPush("您有一个质检项未填报", fr.getMenuName(), fr.getUserId()+"", "1");
					 warningService.insert(w);
    			 }
    		 }
    	 }
     }
}
